package com.gitee.feizns.explore.data_structure.sort;

import java.util.Arrays;

/**
 * @author feizns
 * @since 2020/1/2
 */
public class InsertSort {

    public static void main(String[] args) {
        int[] arr = new int[]{ 2, 3, 1, 4, 5 };
        insertSort2(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int val = arr[i];
            int j = i;
            for (; j > 0 && arr[j - 1] > val; j--)
                arr[j] = arr[j - 1];
            arr[j] = val;
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void insertSort2(int[] arr) {
        for (int i = arr.length - 2; i >= 0; i--) {
            int val = arr[i];
            int index = i + 1;
            for (; index < arr.length && val > arr[index]; index++)
                arr[index - 1] = arr[index];
            if ( index != i + 1 )
                arr[index- 1] = val;
        }
    }

}
